//
//  TSZPhotoCollectionCell.swift
//  微博天下
//
//  Created by Tsz on 15/10/21.
//  Copyright © 2015年 Tsz. All rights reserved.
import UIKit
import SVProgressHUD
import SDWebImage

//定义协议，当捏合屏幕时就去触发转场动画

protocol TSZPhotoCollectionCellDelegate: NSObjectProtocol {
    //cell缩放的放
    func photoCellZoom(scale: CGFloat)
    
    //结束缩放
    func photoCellEndZoom()
}


class TSZPhotoCollectionCell: UICollectionViewCell {
    
    //图片的代理
    weak var photoDelegate: TSZPhotoCollectionCellDelegate?
    
    var imageURL: NSURL? {
        didSet {
            
            //显示 加载
            indicator.startAnimating()
           
            //重新设置scrollerView的偏移量
            resetScrollerView()
            
            //下载图片
            imageView.image = nil
            
            // 模拟延时
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW ,Int64(0)),dispatch_get_main_queue()) { () -> Void in
                self.imageView.sd_setImageWithURL(self.imageURL) { (image, _, _, _) -> Void in
                    
                    //菊花停止
                    self.indicator.stopAnimating()
                    
                    if image == nil {
                        SVProgressHUD.showInfoWithStatus("网络错误", maskType: SVProgressHUDMaskType.Gradient)
                        return
                    }
                    self.setupImagePosition()
                }
            }
        
        }
    }
    
    //MARK: 设置 scrollerView的偏移量
    private func resetScrollerView(){
        scroller.contentInset = UIEdgeInsetsZero
        scroller.contentOffset = CGPointZero
        scroller.contentSize = CGSizeZero
    }
    
    
    //MARK: 计算长短图
    private func setupImagePosition() {
        let s = self.displaySize(imageView.image!)
        
        // 短图居中显示
        if s.height < scroller.bounds.height {
            let y = (scroller.bounds.height - s.height) * 0.5
           
            imageView.frame = CGRect(origin: CGPointZero, size: s)
            //设置间距
            scroller.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
        }else{
            //长图
            imageView.frame = CGRect(origin: CGPointZero, size: s)
            
            //实现滑动
            scroller.contentSize = s
        }
    }
    
    //MARK: 显示 图片的大小
    private func displaySize(image: UIImage) -> CGSize {
        //按比例缩放
        let scale = image.size.height /  image.size.width
        
        let height = scale * scroller.bounds.width
        return CGSize(width: scroller.bounds.width, height: height)
    }
    
    
    //MARK: 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        //准备UI
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 布局UI
    private func setupUI(){
        //添加控件
        contentView.addSubview(scroller)
        
        scroller.addSubview(imageView)
        
        contentView.addSubview(indicator)
        
        scroller.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[SV]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["SV" : scroller]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[SV]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["SV" :scroller]))
        
        indicator.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        
        prepareScroller()
        
        //强制更新子试图的frame
//        layoutIfNeeded()
    }
    //MARK:  捏合的手势是由UIScrollerView
    private func prepareScroller(){
        //这个手势是由代理去完成的
        
        scroller.delegate = self
        scroller.maximumZoomScale = 2.0
        scroller.minimumZoomScale = 0.5
    }
    
    //MARK: 懒加载控件
    private lazy var scroller = UIScrollView()
     lazy var imageView = UIImageView()
    //菊花
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
}

extension TSZPhotoCollectionCell: UIScrollViewDelegate {
    //实现代理方法
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        return imageView
    }
    
    /**
    在缩放完成后，会被调用一次
    - parameter scrollView: scroller
    - parameter view      : 被缩放的view
    - parameter scale     : 缩放完成后的比例
    */
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        //小于0.75就直接解除转场 ，让回去
        if scale >= 0.75 {
            
            //重新计算间距
            var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
            //如果边距小了需要重新修正
            offsetX = offsetX < 0 ? 0: offsetX
            var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
            offsetY = offsetY < 0 ? 0: offsetY
            
            scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        }
        
        //通知代理缩放结束
        photoDelegate?.photoCellEndZoom()
    }
    
    //下列这个方法，只要缩放就会调用
    func scrollViewDidZoom(scrollView: UIScrollView) {

        //通知代理
        photoDelegate?.photoCellZoom(imageView.transform.a)
    }
}

